//
//  leftMenViewController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/29.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "leftMenViewController.h"
#import "WDNavController.h"
#import "ControllerTool.h"
#import "MMDrawerController.h"
#import "MMDrawerBarButtonItem.h"
#import "UIViewController+MMDrawerController.h"
#import "WDLeftMenu.h"
#import "WDLeftMenuCell.h"
#import "WDHead.h"
#import "WDHeadCell.h"
#import "WDPersonDetailController.h"
#import "WDLoanManagerController.h"
#import "WDBusinessManagerController.h"
#import "WDFinancialProductController.h"
#import "WDCompanyAddressController.h"
#import "WDCityOperationViewController.h"
#import "WDPlanTargetViewController.h"
#import "WDMyNotifyController.h"


@interface LeftMenViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSArray *leftMenus;
//是否是第一次加载
@property(nonatomic,assign,getter=isFirst) BOOL first;
///** 记录来自哪个控制器跳转过来的 */
@property (nonatomic, strong) NSString *comeVC;
@property (assign, nonatomic) CGFloat headCellHeight;

@end

@implementation LeftMenViewController

- (void)setDefaultIndex:(NSUInteger)defaultIndex
{
    _defaultIndex = defaultIndex;
    
    self.first = YES;

}
//懒加载数据
- (NSArray *)leftMenus
{
    if (_leftMenus == nil)
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"WDLeftMenu.plist" ofType:nil];
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *leftMenuArr = [NSMutableArray array];
        
        for (NSDictionary *dict in dictArray) {
            
            WDLeftMenu *leftMenu = [WDLeftMenu leftMenuWithDict:dict];
            
            [leftMenuArr addObject:leftMenu];
        }
        _leftMenus = leftMenuArr;
        
    }
    return _leftMenus;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = ColorForRGB(0x545e6a);
    
    self.first = YES;
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNoti:) name:@PostString object:nil];
}

- (void)receiveNoti:(id)obj{
    
//    WDLog(@"%@",[obj valueForKey:@"object"]);
    self.comeVC = [obj valueForKey:@"object"];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //设置头像
    WDHeadCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    NSString *imageURL = [userDefault objectForKey:@"userIcon"];
    
    NSString *name = [userDefault objectForKey:@"personName"];
    
    NSString *accout = [userDefault objectForKey:@"userName"];
    
    cell.head = [WDHead headWithPicture:imageURL name:name email_personal:accout];
    
    //设置statusBar样式
    [self preferredStatusBarStyle];
    
    if (self.isFirst) {
        if (self.defaultIndex == 0) {
            self.defaultIndex = 1;
        }
        
        NSIndexPath *selectPath = [NSIndexPath indexPathForRow:self.defaultIndex inSection:0];
        [self.tableView selectRowAtIndexPath:selectPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        NSIndexPath *path=[NSIndexPath indexPathForItem:self.defaultIndex inSection:2];
        [self tableView:self.tableView didSelectRowAtIndexPath:path];
        self.first = NO;
    }
    
    //查看通知的个数
    [self sendCountRequest];
}

//设置StatusBar样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

#pragma mark - 请求通知的个数
- (void)sendCountRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLGetNotice];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        WDLog(@"%@", responseObject[@"count"]);
        
        if ([responseObject[@"count"] boolValue]) {//有通知
            
            WDLeftMenuCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:(self.leftMenus.count - 1) inSection:0]];
            
            cell.leftMenu = self.leftMenus[self.leftMenus.count - 1];
            
            //设置图标个数
            [UIApplication sharedApplication].applicationIconBadgeNumber = [responseObject[@"count"] integerValue];
            
            [GeTuiSdk setBadge:[responseObject[@"count"] integerValue]];
            
        } else {//没有通知
            
            WDLeftMenuCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:(self.leftMenus.count - 1) inSection:0]];
            
            cell.leftMenu = self.leftMenus[self.leftMenus.count - 2];
            
            //设置图标个数
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            
            [GeTuiSdk setBadge:0];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
//        WDLog(@"%@", error);
        
    }];
    
}

#pragma mark - <tableView代理>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.leftMenus.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        WDHeadCell *cell = [WDHeadCell headCellWithTableView:tableView];
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        
        NSString *imageURL = [userDefault objectForKey:@"userIcon"];
        
        NSString *name = [userDefault objectForKey:@"personName"];
        
        NSString *accout = [userDefault objectForKey:@"userName"];
        
        cell.head = [WDHead headWithPicture:imageURL name:name email_personal:accout];
        
        self.headCellHeight = cell.head.cellH;
        
        return cell;
    } else {
        
        WDLeftMenuCell *cell = [WDLeftMenuCell leftMenuCellWithTableView:tableView];
        
        if (indexPath.row == 1) {//客户贷款
            if ([WDVerify verifyStr:finance_getList inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]])
            {
                cell.hidden = NO;
            } else {
                cell.hidden = YES;
            }
        }
        
        if (indexPath.row == 2) {//商户维系
            if ([WDVerify verifyStr:supplier_getList inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]])
            {
                cell.hidden = NO;
            } else {
                cell.hidden = YES;
            }
        }
        
        if (indexPath.row == 3) {//金融产品
            if ([WDVerify verifyStr:product_getList inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]])
            {
                cell.hidden = NO;
            } else {
                cell.hidden = YES;
            }
        }
        
        if (indexPath.row == 5 || indexPath.row == 6) {
            
            cell.hidden = YES;
            
        }
        
        cell.leftMenu = self.leftMenus[indexPath.row - 1];
        
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        [self openViewControllerWithIndex:indexPath.row];
        
    } else {
        
        [self openViewControllerWithIndex:indexPath.row];
        //遍历所有cell，将选中的设为选中，没选中的设为透明
        for (NSUInteger index = 0; index < self.leftMenus.count; index ++) {
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            if (index == indexPath.row) { //选中cell
                cell.backgroundColor = ColorForRGB(0x6F7B87);
            }else { //非选中的cell
                cell.backgroundColor = [UIColor clearColor];
            }
        }
    }
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        return self.headCellHeight;
        
    }else if (indexPath.row == 1) {
        
        //客户贷款
        if ([WDVerify verifyStr:finance_getList inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]])
        {
            return WDScale(49);
            
        } else {
            
            return 0;
        }
        
    } else if (indexPath.row == 2) {
        
        //商户维系
        if ([WDVerify verifyStr:supplier_getList inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]])
        {
            return WDScale(49);
            
        } else {
            
            return 0;
        }
        
    } else if (indexPath.row == 3) {
        
        //金融产品
        if ([WDVerify verifyStr:product_getList inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]])
        {
            return WDScale(49);
            
        } else {
            
            return 0;
        }
        
    } else if (indexPath.row == 5 || indexPath.row == 6){
        
        return 0;
        
    } else {
        
        return WDScale(49);
    }
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}


- (void)openViewControllerWithIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
        {
            WDPersonDetailController *tempVC = [[WDPersonDetailController alloc] init];
            tempVC.comeVC = self.comeVC;
            tempVC.view.backgroundColor = WDBackColor;

            
            /*设置中间的控制器*/
            //[self.mm_drawerController setCenterViewController:[[WDNavController alloc] initWithRootViewController:tempVC]];
            WDLog(@"%@", self.mm_drawerController.centerViewController);
            [(WDNavController *)self.mm_drawerController.centerViewController pushViewController:tempVC animated:YES];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
            break;
        case 1:
        {
            //第一次加载
            static WDNavController *navVC = nil;
//                        static dispatch_once_t onceToken;
//                        dispatch_once(&onceToken, ^{
            WDLoanManagerController *goodVC = [[WDLoanManagerController alloc] init];
            navVC = [[WDNavController alloc] initWithRootViewController:goodVC];
//                        });
            
            /*设置中间的控制器*/
            [self.mm_drawerController setCenterViewController:navVC];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
            break;
        case 2:
        {
            //第一次加载
            static WDNavController *navVC = nil;
//                        static dispatch_once_t onceToken;
//                        dispatch_once(&onceToken, ^{
            WDBusinessManagerController *goodVC = [[WDBusinessManagerController alloc] init];
            navVC = [[WDNavController alloc] initWithRootViewController:goodVC];
//                        });
            
            /*设置中间的控制器*/
            [self.mm_drawerController setCenterViewController:navVC];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
            break;
        case 3:
        {
            //第一次加载
            static WDNavController *navVC = nil;
//                        static dispatch_once_t onceToken;
//                        dispatch_once(&onceToken, ^{
            WDFinancialProductController *goodVC = [[WDFinancialProductController alloc] init];
            navVC = [[WDNavController alloc] initWithRootViewController:goodVC];
//                        });
            
            /*设置中间的控制器*/
            [self.mm_drawerController setCenterViewController:navVC];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
            break;
        case 4:
        {
            //第一次加载
            static WDNavController *navVC = nil;
//                        static dispatch_once_t onceToken;
//                        dispatch_once(&onceToken, ^{
            WDCompanyAddressController *goodVC = [[WDCompanyAddressController alloc] init];
            navVC = [[WDNavController alloc] initWithRootViewController:goodVC];
//                        });
            
            /*设置中间的控制器*/
            [self.mm_drawerController setCenterViewController:navVC];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
            break;
            
        case 5:
        {
            //第一次加载
            static WDNavController *navVC = nil;
//                        static dispatch_once_t onceToken;
//                        dispatch_once(&onceToken, ^{
            WDPlanTargetViewController *goodVC = [[WDPlanTargetViewController alloc] init];
            navVC = [[WDNavController alloc] initWithRootViewController:goodVC];
//                        });
            
            /*设置中间的控制器*/
            [self.mm_drawerController setCenterViewController:navVC];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
            break;
            
        case 6:
        {
            //第一次加载
            static WDNavController *navVC = nil;
//                        static dispatch_once_t onceToken;
//                        dispatch_once(&onceToken, ^{
            WDCityOperationViewController *goodVC = [[WDCityOperationViewController alloc] init];
            navVC = [[WDNavController alloc] initWithRootViewController:goodVC];
//                        });
            
            /*设置中间的控制器*/
            [self.mm_drawerController setCenterViewController:navVC];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
            break;
            
        case 7:
        {
            //第一次加载
            static WDNavController *navVC = nil;
            
//                        static dispatch_once_t onceToken;
//                        dispatch_once(&onceToken, ^{
            WDMyNotifyController *goodVC = [[WDMyNotifyController alloc] init];
            goodVC.view.backgroundColor = [UIColor whiteColor];
            navVC = [[WDNavController alloc] initWithRootViewController:goodVC];
//                        });
            
            /*设置中间的控制器*/
            [self.mm_drawerController setCenterViewController:navVC];
            
            //关闭抽屉控制器
            [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
        }
    }
}

#pragma mark - 懒加载
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:self.defaultIndex inSection:0];
        
        [_tableView selectRowAtIndexPath:indexpath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
    return _tableView;
}

- (void)dealloc
{
    WDLog(@"%s",__func__);
}


@end
